package ch.ffhs.radarpp.service;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import ch.ffhs.radarpp.managers.PersistentDataManager;
import ch.ffhs.radarpp.managers.WebRequestManager;
import ch.ffhs.radarpp.model.Settings;
import ch.ffhs.radarpp.web.WebClient;
import ch.ffhs.radarpp.web.WebManager;
/**
 * 
 * @author Beda
 *
 */
public class GPSService extends Service implements LocationListener, WebClient {

	private Timer timer = null;
	private Location lastLocation = null;
	private WebManager webManager;
	private LocationManager locationManager;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		timer.cancel();
		locationManager.removeUpdates(this);

		return super.onUnbind(intent);
	}

	@Override
	public void onDestroy() {

		timer.cancel();
		locationManager.removeUpdates(this);

		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		Settings s = PersistentDataManager.getAppSettings(this);

		webManager = new WebManager(this, s);
		timer = new Timer("GPSUpdateTimer");

		timer.scheduleAtFixedRate(new TimerTask() {

			@Override
			public void run() {

				if (lastLocation != null) {

					String requestUrl = WebRequestManager.createDeployLocationRequest(GPSService.this, lastLocation.getLatitude(), lastLocation.getLongitude());

					webManager.executeHTTPRequest(requestUrl);
				}

			}
		}, 0, s.getGPSTimeInterval() * 1000);

		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

			if (s.isGPSEnabled()) {
				locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, s.getGPSTimeInterval() * 1000, 10, this);
			}

			if (s.isNetworkEnabled()) {
				locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, s.getGPSTimeInterval() * 1000, 200, this);
			}

			if (s.isPassiveEnabled()) {
				locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, s.getGPSTimeInterval() * 1000, 200, this);
			}

			lastLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
		}

		return Service.START_STICKY;
	}

	@Override
	public void onLocationChanged(Location location) {
		lastLocation = location;
	}

	@Override
	public void onProviderDisabled(String provider) {

	}

	@Override
	public void onProviderEnabled(String provider) {

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {

	}

	@Override
	public void requestCompleted(String result, Object context) {
		
	}

	@Override
	public void requestFailed(Exception e, Object context) {

	}

}
